//
//  MTPersonAuthController.swift
//  MT
//
//  Created by 陈悦 on 2020/5/30.
//  Copyright © 2020 张强. All rights reserved.
//

import Moya
import Result
import RxSwift
import RxCocoa
import MTCategory

class MTPersonAuthController: BaseViewController {
    /// MTProvider
    private lazy var provider: MTProvider<UploadApi> = {
        return MTProvider<UploadApi>(plugins: [])
    }()
    private let disposeBag = DisposeBag()
    
    private lazy var user_provider: MTProvider<MineApi> = {
        return MTProvider<MineApi>(plugins: [])
    }()
    
    var model: MTCerSummarySubModel? {
        didSet {
            guard let model = model else { return }
            if model.personCertification?.douyinHomePage?.count ?? 0 > 0 {
                imageArr.append(27)
            }
            if model.personCertification?.kuaishouHomePage?.count ?? 0 > 0 {
                imageArr.append(28)
            }
            if model.personCertification?.xiaohongshuHomePage?.count ?? 0 > 0 {
                imageArr.append(29)
            }
            if model.personCertification?.otherHomePage?.count ?? 0 > 0 {
                imageArr.append(30)
            }
            countLabel.text = "已上传\(imageArr.count)/4"
            tiktokUrl = model.personCertification?.douyinHomePage
            kuaishouUrl = model.personCertification?.kuaishouHomePage
            redUrl = model.personCertification?.xiaohongshuHomePage
            otherUrl = model.personCertification?.otherHomePage
//            self.tableView.reloadData()
        }
    }
    
    /// 列表控制数组
    private var infoTypes: [UserProfileInfos] = [.TiktokShot, .KuaishouShot,.RedShot,.OtherShot]
    

    ///抖音
    var tiktokUrl: String?
    ///快手
    var kuaishouUrl: String?
    ///小红书
    var redUrl: String?
    ///其他
    var otherUrl: String?
    
    var imageArr: [Int] = []
    
    var currentUploadType = -1
    
    lazy var tableView: UITableView = {
        let tv = UITableView(frame: self.view.bounds, style: .grouped)
        tv.dataSource = self
        tv.delegate = self
        tv.separatorStyle = .none
        tv.keyboardDismissMode = .onDrag
        tv.showsVerticalScrollIndicator = false
        tv.tableFooterView = UIView()
        tv.backgroundColor = UIColor(hex: 0xf6f6f6)
        
        for type in infoTypes {
            tv.register(type.cellClass, forCellReuseIdentifier: String(describing: type.cellClass))
        }

        return tv
    }()
    
    lazy var commitButton: UIButton = {
        let btn = UIButton()
        btn.setTitle("提交申请", for: .normal)
        btn.setTitleColor(.white, for: .normal)
        btn.titleLabel?.font = PingFangSCSemiboldFont(16)
        btn.adjustsImageWhenHighlighted = false
        btn.layer.cornerRadius = 25
        btn.backgroundColor = UIColor(hex:0xffc000)
        btn.clipsToBounds = true
        btn.addTarget(self, action: #selector(personAuthController(didClickCommitButton:)), for: .touchUpInside)
        return btn
    }()
    
    lazy var countLabel: UILabel = {
        let label = UILabel()
        label.text = "已上传0/4"
        label.font = PingFangSCMediumFont(14)
        label.textColor = UIColor.text.x9b9b9b
        return label
    }()
    
    deinit {
        removeNotifications()
    }
}

// MARK: ------------------------------------ Overrides ----------------------------------------
extension MTPersonAuthController {
    
    override func viewDidLoad() {
        super.viewDidLoad()
        addNotifications()
//        loadData()
        initializeUI()
    }
}

// MARK: ---------------------------------------- 初始化 --------------------------------------------
extension MTPersonAuthController {
    
    
    private func initializeUI() {
        view.backgroundColor = UIColor(hex: 0xf6f6f6)
        navigationItem.title = "个人认证"
        
        view.addSubview(tableView)
        tableView.snp.makeConstraints { (make) in
            make.edges.equalTo(view)
        }
        
        view.addSubview(commitButton)
        commitButton.snp.makeConstraints { (make) in
            make.left.equalTo(view).offset(20)
            make.right.equalTo(view).offset(-20)
            make.height.equalTo(50)
            make.bottom.equalTo(view).offset(-ScreenBottomExtraOffset - 20)
        }
    }
}

// MARK: ------------------------------------ 所有代理 ----------------------------------------
// MARK: ------------------------------------ UITableViewDelegate ----------------------------------------
extension MTPersonAuthController: UITableViewDelegate {
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {

    }
    
}
// MARK: ------------------------------------ UITableViewDataSource ----------------------------------------
extension MTPersonAuthController: UITableViewDataSource {
    
    func numberOfSections(in tableView: UITableView) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return infoTypes.count
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return infoTypes[indexPath.row].cellHeight
    }

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let type = infoTypes[indexPath.row]
        let c = tableView.dequeueReusableCell(withIdentifier: String(describing: type.cellClass), for: indexPath)

        switch type {

        case .TiktokShot,.RedShot,.KuaishouShot,.OtherShot:
            guard let cell = c as? MTInfoVerificationPortraitCell else {
                break
            }
//            cell.delegate = self
//            cell.models = self.imgList
            cell.type = type
            switch type {
            case .TiktokShot:
                cell.loadURL = tiktokUrl
                break
            case .KuaishouShot:
                cell.loadURL = kuaishouUrl
                break
            case .RedShot:
                cell.loadURL = redUrl
                break
            case .OtherShot:
                cell.loadURL = otherUrl
                break
            default:
                break
            }
            return cell
            
        default: break
        }
        
        return c
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 30
    }
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 50
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 30))
        view.backgroundColor = UIColor(hex:0xf6f6f6)
        view.addSubview(countLabel)
        countLabel.frame = CGRect(x: 10, y: 0, width: 300, height: 30)
        return view
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let view = UIView(frame: CGRect(x: 0, y: 0, width: ScreenWidth, height: 10))
        view.backgroundColor = UIColor(hex:0xf6f6f6)
        let label = UILabel(frame: CGRect(x: 10, y: 10, width: ScreenWidth-20, height: 40))
        label.numberOfLines = 0
        label.text = "规则：至少上传两条信息，其他选择上传（上传越多审核通过几率越高哦～）"
        label.textColor = UIColor.text.x9b9b9b
        label.font = PingFangSCMediumFont(12)
        view.addSubview(label)
        return view
    }
    
}

// MARK: ------------------ 通知相关 ----------------------
extension MTPersonAuthController {
    
    private func addNotifications() {
        NotificationCenter.default.addObserver(self, selector: #selector(presentPhotoLibrary), name: GlobalNotificationName.presentPhotoLibrary.name, object: nil)
    }

    private func removeNotifications() {
        NotificationCenter.default.removeObserver(self, name: GlobalNotificationName.presentPhotoLibrary.name, object: nil)
    }
    
}

// MARK: ------------------------------------ 相册 ----------------------------------------
@objc extension MTPersonAuthController {
    
    private func presentPhotoLibrary(noti: Notification) {
        let type: Int = noti.userInfo?["type"] as! Int
        currentUploadType = type
        if imageArr.count > 0 {
            for (index,value) in imageArr.enumerated() {
                if value == type {
                    imageArr[index] = type
                    break
                } else {
                    imageArr.append(type)
                    break
                }
            }
        } else {
            imageArr.append(type)
        }
        let c = PhotoLibraryViewController()
        c.delegate = self
        c.maxSelectdCount = 1
        c.allowVideoSelection = false
        let nav = BaseNavController(rootViewController: c)
        nav.modalPresentationStyle = .fullScreen
        self.present(nav, animated: true, completion: nil)
    }
    
}

// MARK: ------------------------------------ 相册代理回调 ----------------------------------------
extension MTPersonAuthController: PhotoLibraryViewControllerDelegate {
        func photoLibraryController(_ controller: PhotoLibraryViewController, didSelectAssetWith asset: MTAsset) {
            MTAssetLibrary.default.requestImage(withAsset: asset.asset) { [weak self] (image, info, isDegraded) in
                guard let weakself = self else { return }
                guard let image = image else { return }
                if isDegraded == false {
                    weakself.uploadImage(image: image)
                }
            }
        }
}

// MARK: ------------------------------------ 上传图片 ----------------------------------------
extension MTPersonAuthController {
    private func uploadImage(image: UIImage) {
        /// 添加 indicator
        _ = self.provider.originRequest(.upload(image), callbackQueue: nil, progress: nil) { [weak self] (result, isCache) in

            /// 取消 indicator
            guard let weakSelf = self else { return }
            switch result {
            case let .success(response):
                guard let dict = try? response.mapJSON() as? [String:Any], let code = dict["code"] as? Int else { return }
                if code == 200, let imageUrl = dict["result"] as? String  {
                    weakSelf.countLabel.text = "已上传\(weakSelf.imageArr.count)/4"
                    if weakSelf.currentUploadType == 27 {
                        weakSelf.tiktokUrl = imageUrl
                    } else if weakSelf.currentUploadType == 28 {
                        weakSelf.kuaishouUrl = imageUrl
                    } else if weakSelf.currentUploadType == 29 {
                        weakSelf.redUrl = imageUrl
                    } else if weakSelf.currentUploadType == 30{
                        weakSelf.otherUrl = imageUrl
                    }
                    
                    DispatchQueue.main.async {
                        weakSelf.tableView.reloadData()
                    }
                } else {
                    DispatchQueue.main.async {
                        AlertManager.presentAlertView(message: "上传照片失败")
                    }
                }
                break

            case let .failure(error):
                DispatchQueue.main.async {
                    AlertManager.presentAlertView(message: error.localizedDescription)
                }
                break

            }
        }
    }
}

// MARK: ---------------------------------------- 事件方法 --------------------------------------------
@objc
extension MTPersonAuthController {
    private func personAuthController(didClickCommitButton sender: UIButton) {
        guard imageArr.count >= 2 else {
            MBProgressHUD_JChat.show(text: "请至少填写两条信息", view: self.view, 1)
            return
        }
        let params: [String: Any] = ["douyinHomePage"    : tiktokUrl ?? "",
                                     "kuaishouHomePage"   : kuaishouUrl ?? "",
                                     "otherHomePage"   : otherUrl ?? "",
                                     "xiaohongshuHomePage"   : redUrl ?? ""]
        user_provider.rx.requestResult(.personalApply(params)).subscribe(onNext: { [weak self] (result: Result<MTWithdrawReportModel, AnyError>, isCache: Bool) in
            guard let weakself = self else { return }
            switch result {
            case let .success(response):
                if response.code == 200 {
                    UIAlertController.rx.show(in: weakself, title: "提交成功", message: "审核需要3-5个工作日，请注意查看消息", buttons: [ .default("确定")]).subscribe(onSuccess: {index in
                        if index == 0 {
                            weakself.navigationController?.popToRootViewController(animated: true)
                        }
                    })
                } else {
                    AlertManager.presentAlertView(message: response.message ?? "")
                }
                break
                
            case let .failure(error):
                AlertManager.presentAlertView(message: error.localizedDescription)
                break
            }
        }).disposed(by: disposeBag)
    }
    
}


